<template>
  <view class="diary-detail" :style="{paddingTop: height + 'px'}">
    <view class="diary-header"   :style="{backgroundColor: '#fff', height: height + 'px'}"> 
      <view class="navbar-com"  :style="{height: boundRect?.top + 'px'}" > </view>
      <view class="diary-header-left" :style="{height: boundRect?.height + 'px'}"  >
        <nut-icon name="left" size="18" @click="backPage" ></nut-icon>
        <image class="avatar" mode="aspectFill" :src="diary?.user['avatar']" />
        <view class="title">{{diary?.user.name}}</view>
      </view>
    </view>

    <view class="diary-card"  >
      <nut-skeleton v-if="loadingDiary" width="320px" height="15px" title animated row="24"> </nut-skeleton>
      <block  v-else>
        <!-- 日记头部 -->
        <view class="header">
          <view class="header-left">
            <text class="date">{{ diary?.time ? dayjs(diary.time).format('MM月DD日') : '' }}</text>
            <text class="week">{{ diary?.time ? dayjs(diary.time).format('dddd') : '' }}</text>
          </view>
          <view class="edit" @click="handleEdit" v-if="isMyDiary">
            <image class="edit-icon" mode="" src="/static/common/edit.png" /> 
            <text>编辑日记</text>
          </view>
        </view>

        <!-- 日记内容 -->
        <view class="diary-content">
          <text>{{diary?.content}}</text>
        </view>
      </block>

      <!-- 表情区域 -->
      <!-- <view class="emojis">
        <view class="emoji-item" v-for="(emoji, index) in emojiList" :key="index">
          <image :src="emoji.icon" mode="aspectFit"/>
          <text>{{emoji.count}}</text>
        </view>
      </view> -->

      <!-- 底部操作栏 -->
      <!-- <view class="footer">
        <view class="publish-time">发布于 {{diary?.time}}</view>
        <view class="actions">
          <view class="action-item" @click="handleComment">
            <image class="icon" mode="aspectFill" src="/static/common/message.png"/>
            <text class="count">{{0}}</text>
          </view>
          <view class="action-item" @click="handleLike">
            <image class="icon" mode="aspectFill" :src="isLiked ? '/static/common/like.png' : '/static/common/unlike.png'"/>
            <text class="count">{{diary?.allLikeCount}}</text>
          </view>
        </view>
      </view> -->
    </view>

    <!-- 点赞头像列表 -->
    <!-- <view class="likes-section" v-if="diary?.allLikeCount > 0">
      <view class="likes-header">
        <image class="like-icon" mode="aspectFill" src="/static/common/like.png"/>
        <text>{{diary?.allLikeCount}}人觉得很赞</text>
      </view>
      <view class="avatars">
        <image 
          v-for="(avatar, index) in likeAvatars" 
          :key="index" 
          :src="avatar"
          mode="aspectFill"
        />
      </view>
    </view> -->
    
    <!-- <view class="divider"></view> -->

    <!-- 没有评论时 -->
    <empty-com desc="快来评论吧" v-if="loadingDiary == false && messageList.length === 0" />

    <!-- 评论列表 -->
    <view class="comment-section"  v-if="messageList.length > 0">
      <view class="comment-header">
        <text class="title">共{{messageList.length}}条评论</text>
      </view>
      <view class="comment-list">
        <view 
          class="comment-item" 
          v-for="item in messageList" 
          :key="item.id"
        >
          <view class="main-comment" @click="openReplyMessageModal(item, 1)">
            <commentCom :itemData="item" type="reply" />
          </view>
          <view
            class="reply-comment"
            v-for="reply in item.messageMore.messageList" 
            :key="reply.id"
            @click="openReplyMessageModal(item, 2)"
          > 
            <commentCom :itemData="reply" type="message" />
          </view>
          <view class="expand-comment" @click="expandComment(item)" v-if="item.messageMore.messageList.length !== item.messageMore.moreCount" > 
            <view class="text" >展开更多回复</view>
            <image mode="aspectfill" src="/static/common/arrow-bottom.png" />
          </view>
        </view>
      </view>
    </view>

    <no-more v-if="queryParams.final && messageList.length > 0" />
  </view>
<!-- :target-user="currentUser" -->
  <input-com
    :show="replayMessageModalShow"
    :target-user="currentUser"
    @confirm="confirm"
    @close="closeReplyMessageModal"
  />

  <!-- 底部回复框 -->
   <reply-com 
    @reply="openReplyDiaryModal"
    :itemData="diary"
   />
</template>

<script lang='ts'  setup >
// import { row } from 'mathjs';
import { onLoad, onReachBottom } from '@dcloudio/uni-app';
import { ref, computed } from 'vue';
import { DiaryController } from '@/controller'
import commentCom from '@/components/comment-com/comment-com.vue'
import InputCom from '@/components/input-com/input-com.vue'; 
import dayjs from 'dayjs'
import ReplyCom from '@/components/reply-com/index.vue'
import { useUserStore } from '@/store/index'
import { storeToRefs } from 'pinia'
import EmptyCom from '@/components/empty-com/empty-com.vue'
import NoMore from '@/components/no-more-com/index.vue'


 const diary = ref<API.DIARY>()

 const diaryId = ref('')

 const userStore = useUserStore()
 
  // 当前回复的类型 diary就是在回复日记 message就是在回复评论
 const replyType = ref<'diary' | 'message'>('diary')

 const { userinfo } = storeToRefs(userStore)

 const queryParams = ref({
  page: 1,
  total: 0,
  pageSize: 2,
  final: false
 })
//  当前回复的级别
 const replyLevel = ref(1)  // 1 or 2  1是一级评论 2是二级评论

 const messageList = ref<API.MESSAGE[]>([])

 const replayMessageModalShow = ref(false)

 const currentUser = ref()

 const loadingDiary = ref(false)

 const currentMessage = ref<Partial<API.MESSAGE> & {page: number}>({
  page: 2 // 每次遇到不同的messageid 这个值置为2
 })

 const isMyDiary = computed(() => currentUser.value.id === userinfo.value.id)

 const handleEdit = () => {
   console.log('handleEdit');
 }

 const backPage = () => uni.navigateBack({delta: 1})

 const getMessageByDiaryId = async () => {
  loadingDiary.value = true
  const { total, data } = await DiaryController.getMessageByDiaryId(diaryId.value, queryParams.value.page, queryParams.value.pageSize)
  loadingDiary.value = false
  queryParams.value.total = total
  if (messageList.value.length < total) {
    messageList.value.push(...data) 
  }

  if ( messageList.value.length >= total) {
    queryParams.value.final = true
  }

 }

 
 const getDiaryByDiaryId = async () => {
  const { data } = await DiaryController.byId(diaryId.value)
  diary.value = data
  currentUser.value = data?.user
 }

const closeReplyMessageModal = () => {
  replayMessageModalShow.value = false
}

// 根据一级评论id获取二级评论
const getLevel2MeessageByMessageId = async (messageId: string, page: number) => {
  const { data } = await DiaryController.getLevel2MessgaeByMessageId(messageId, page)
  return data
}


const confirm = (message: string) => {
  // getMessageByDiaryId()
  if (replyType.value === 'diary') {
    replyDiary(message) 
  } else {
    replyMessage(message)
  }
  getMessageByDiaryId()
}

const openReplyDiaryModal = () => {
  replayMessageModalShow.value = true
  replyType.value = 'diary'
}


const openReplyMessageModal = async (item: API.MESSAGE, level: 1 | 2) => {
  currentMessage.value = {
    ...item,
    page: 1
  }
  replayMessageModalShow.value = true
  currentUser.value = item.user
  replyType.value = 'message'
  replyLevel.value = level
}

const closeReplyModal = () => {
  replayMessageModalShow.value = false
}

const replyDiary = async (message: string) => {
  const status = await DiaryController.addDiaryMessage({
    content: message,
    dailyId: diaryId.value,
  } as API.MESSAGE)
  if (status === 200) {
    closeReplyModal()
  }
}

const replyMessage = async (message: string) => {

  const $par = {
    content: message,
    dailyId: diaryId.value,
    replyId: currentMessage.value?.id || '',
  }
  const status = await  DiaryController.addReplyDiaryMessage({
    ...$par,
    replySecondUserId: replyLevel.value === 2 ?  currentMessage.value!.user.id : '',
    replySecondUserName:  replyLevel.value === 2 ?  currentMessage.value!.user.name : ''
  } as API.MESSAGE ) 
  if (status === 200) {
    closeReplyModal()
  }

}

const expandComment = async (records: API.MESSAGE) => {
  if (currentMessage.value.id === records.id) {
    currentMessage.value.page += 1 
  } else {
    currentMessage.value = {
      ...records,
      page: 2
    }
  }
  const data = await getLevel2MeessageByMessageId(records.id!, currentMessage.value.page)
  console.log('data:', data);
  
  records.messageMore.messageList.push(...data)
  console.log('records.messageMore.messageList:', records.messageMore.messageList);
  
}

  onReachBottom(() => {
    if (messageList.value.length != 0) {
      queryParams.value.page++
      getMessageByDiaryId()
    }
 
    console.log('onReachBottom');
  })

  const boundRect = ref()

  const height = ref(0)


 onLoad((options: any) => {
  console.log('options:', options);
  
  diaryId.value = options.diaryId
  getMessageByDiaryId()
  getDiaryByDiaryId()

  const res = uni.getMenuButtonBoundingClientRect()
  boundRect.value = res
  height.value = res.bottom + 12
 })


</script>
<style lang='scss' scoped>
@import '../../styles/index.scss';

.diary-detail {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: 480rpx;
  // padding-top: 24rpx;
  .diary-header {
    width: 100vw;
    position: fixed;
    left: 0;
    top: 0;
    .navbar-com {
      width: 100vw;
    }
    .diary-header-left {
      height: 100%;
      display: flex;
      align-items: center;
      padding-left: 48rpx;
      box-sizing: border-box;
      .back-icon {
        width: 45px;
        height: 45px;
      }
      .avatar {
        width: 80rpx;
        height: 80rpx;
        border-radius: 50%;
        margin-left: 24rpx;
        margin-right: 24rpx;
      }
    }
  }
  // 日记卡片
  .diary-card {
    margin: 24rpx;
    margin-bottom: 0px;
    padding: 32rpx;
    background-color: #fff;
    border-top-left-radius : 16rpx;
    border-top-right-radius: 16rpx;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);

    .header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 32rpx;

      &-left {
        .date {
          font-size: 32rpx;
          font-weight: 600;
          color: $text-grey;
          margin-right: 16rpx;
        }

        .week {
          font-size: 28rpx;
          color: $text-grey;
        }
      }

      .edit {
        display: flex;
        align-items: center;
        padding: 12rpx 24rpx;
        background-color: #f5f5f5;
        border-radius: 32rpx;
        
        &-icon {
          width: 28rpx;
          height: 28rpx;
          margin-right: 8rpx;
        }

        text {
          font-size: 24rpx;
          color: $text-grey;
        }
      }
    }

    .diary-content {
      font-size: 30rpx;
      line-height: 1.8;
      color: $text-grey;
      margin-bottom: 32rpx;
    }

    .emojis {
      display: flex;
      flex-wrap: wrap;
      gap: 16rpx;
      margin-bottom: 32rpx;

      .emoji-item {
        display: flex;
        align-items: center;
        padding: 8rpx 16rpx;
        background-color: #f5f5f5;
        border-radius: 24rpx;

        image {
          width: 32rpx;
          height: 32rpx;
          margin-right: 8rpx;
        }

        text {
          font-size: 24rpx;
          color: $text-grey;
        }
      }
    }

    .footer {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding-top: 24rpx;
      border-top: 2rpx solid #f5f5f5;

      .publish-time {
        font-size: 26rpx;
        color: $text-grey;
      }

      .actions {
        display: flex;
        gap: 32rpx;

        .action-item {
          display: flex;
          align-items: center;
          
          .icon {
            width: 36rpx;
            height: 36rpx;
            margin-right: 8rpx;
          }

          .count {
            font-size: 26rpx;
            color: $text-grey;
          }
        }
      }
    }
  }

  // 点赞区域
  .likes-section {
    margin: 24rpx;
    padding: 24rpx;
    background-color: #fff;
    border-radius: 16rpx;

    .likes-header {
      display: flex;
      align-items: center;
      margin-bottom: 16rpx;

      .like-icon {
        width: 32rpx;
        height: 32rpx;
        margin-right: 12rpx;
      }

      text {
        font-size: 28rpx;
        color: $text-grey;
      }
    }

    .avatars {
      display: flex;
      flex-wrap: wrap;
      gap: 12rpx;

      image {
        width: 64rpx;
        height: 64rpx;
        border-radius: 50%;
        border: 2rpx solid #fff;
        box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
      }
    }
  }

  .divider {
    height: 16rpx;
    background-color: #f8f8f8;
  }

  // 评论区域
  .comment-section {
    margin: 24rpx;
    padding: 24rpx;
    background-color: #fff;
    border-bottom-left-radius : 16rpx;
    border-bottom-right-radius: 16rpx;
    margin-top: 0rpx;
    border-top: 1px solid #f8f8f8;
    .comment-header {
      margin-bottom: 24rpx;
      .title {
        font-size: 24rpx;
        font-weight: 600;
        color: $text-grey;
      }
    }

    .comment-list {
      .comment-item {
        margin-bottom: 48rpx;

        .main-comment {
          margin-bottom: 38rpx;
        }

        .reply-comment {
          margin-left: 78rpx;
          // padding-left: 24rpx;
          // border-left: 2rpx solid #f5f5f5;
          margin-bottom: 24rpx;
        }
        .expand-comment {
          margin-top: 12rpx;
          color: $text-grey;
          font-size: 28rpx;
          display: flex;
          align-items: center;
          margin-left: 88rpx;
          .text {
            margin-right: 12rpx;
          }
          image {
            width: 20rpx;
            height: 20rpx;
          }
        }
      }
    }
  }
}
</style>